package me.teacms.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.glassfish.external.probe.provider.annotations.ProbeParam;
import me.teacms.common.result.JsonResult;
import me.teacms.dao.CommonMapper;
import me.teacms.dao.MultimediaMapper;
import me.teacms.entity.Category;
import me.teacms.entity.Multimedia;
import me.teacms.entity.Tag;
import me.teacms.entity.User;
import me.teacms.entity.vo.ArticleAllVo;
import me.teacms.entity.vo.ArticleNewVo;
import me.teacms.service.ArticleEditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Author: XiaoBingBy
 * Email: XiaoBingBy@qq.com
 * Date: 2017/2/27
 * Time: 16:37
 * Describe: 编辑文章
 */
@Controller
@RequestMapping("/admin")
public class ArticleEditController {

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private ArticleEditService articleEditService;
    @Autowired
    private MultimediaMapper multimediaMapper;

    @RequestMapping("/article-edit.html")
    public String articleEdit(ModelMap modelMap, @ProbeParam("id") Integer id, @ProbeParam("edit") String edit) {

        List<Category> allCategory = commonMapper.findAllCategory();
        List<Tag> allTag = commonMapper.findAllTag();
        PageHelper.startPage(0, 12);

        /**
         * 插入图片
         */
        List<Multimedia> allImg = multimediaMapper.findAllImg(null);
        PageInfo allImgInfo = new PageInfo(allImg);

        modelMap.put("allCategory", allCategory);
        modelMap.put("allTag", allTag);
        modelMap.put("allImgInfo", allImgInfo.getList());

        if (id == null) {
            return "_admin/article/article_new";
        }
        /* 查询传入ID的文章*/
        ArticleAllVo  article = articleEditService.findArticById(id);
        modelMap.put("article", article);

        return "_admin/article/article_edit";
    }

    /**
     * 更新文章
     * @param session
     * @param articleNewVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatearticle")
    public JsonResult updateArticle(HttpSession session, ArticleNewVo articleNewVo) {

        /**
         * 添加用户信息
         */
        User user = (User) session.getAttribute("user");
        articleNewVo.setArticleAuthor(user.getId());
        JsonResult jsonResult = articleEditService.updateArticle(articleNewVo);

        return jsonResult;
    }

}
